// 遍历所有的messages文件，并生成zh.json文件

const { glob } = require('glob');
const fs = require('fs');
const parser = require('@babel/parser');
const t = require('@babel/types');
// const generator = require('@babel/generator')
const prettier = require('prettier'); // 代码优化
const traverse = require('@babel/traverse').default;

const prettierOptions = {
  // 这里配置你想要的Prettier选项
  parser: 'json-stringify',
  semi: false,
  singleQuote: true,
  trailingComma: 'all',
};

const jsonFilePath = './zh.json';
async function main() {
  let directory = process.argv[2]; // 文件目录

  if (!directory) {
    // 如果没有目录，则从根目录开始
    directory = './';
  }
  const files = await glob('**/messages.js', { cwd: directory });
  let full_map = new Map();
  console.log('files', files);
  for (let index = 0; index < files.length; index++) {
    const fileDir = files[index];
    const file = fs.readFileSync(fileDir, 'utf-8');
    const astCode = parser.parse(file, {
      sourceType: 'module',
      plugin: ['jsx'],
    });
    const [map] = transFile(astCode);
    full_map = [...full_map, ...map];
    createLangueFile(full_map);
  }
}

function transFile(astCode) {
  const map = new Map();
  traverse(astCode, {
    CallExpression(path) {
      if (
        t.isIdentifier(path.node.callee, { name: 'defineMessages' }) &&
        path.node.arguments.length === 1 &&
        t.isObjectExpression(path.node.arguments[0])
      ) {
        const node = path.node.arguments[0];
        console.log('node', node);
        node.properties.forEach((item, index) => {
          const value = item.value.properties[1].value.value;
          const key = item.value.properties[0].value.value;
          map.set(key, value);
        });
      }
    },
  });
  return [map];
}

async function createLangueFile(map) {
  const obj = Object.fromEntries(map);
  let code = JSON.stringify(obj);
  code =  await prettier.format(code, prettierOptions);
  console.log('obj', obj);
  const filePath = jsonFilePath;
  fs.writeFileSync(filePath, code);
}

main();
